package com.goambu.driver.autenticacion.controller;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import com.goambu.driver.GoAmbuDriverConstants;
import com.goambu.driver.autenticacion.entities.AlertaBean;
import com.goambu.driver.autenticacion.entities.CentroMedicoBean;
import com.goambu.driver.autenticacion.entities.GeocoderResponse;
import com.goambu.driver.autenticacion.entities.LocationBean;
import com.goambu.driver.framework.controller.internet.HttpConnector;
import com.goambu.driver.utils.MyGeocoder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class CentrosMedicosController {
	public static CentrosMedicosController instance = null;
	public ArrayList<CentroMedicoBean> centrosMedicos = null;
	
	
	public static CentrosMedicosController getInstance() {
		if (instance == null) {
			instance = new CentrosMedicosController();

		}
		return instance;
	}

	public ArrayList<CentroMedicoBean> getCentrosMedicosByOrg() {
		String path = GoAmbuDriverConstants.SERVER_URL
				+ String.format(
						GoAmbuDriverConstants.CENTROSMEDICOS_GETCENTROSMEDICOS,
						AutenticacionController.getInstance().currentUser.worker.organizationId);

		Gson gs = new Gson();
		String strResponse;
		ArrayList<CentroMedicoBean> objResponse = null;
		CentroMedicoBean centroMedico = null; 

		HttpResponse respuesta = HttpConnector.makeGetRequest(path, "");

		if (respuesta != null) {
			try {
				strResponse = EntityUtils.toString(respuesta.getEntity());
				Type listType = new TypeToken<ArrayList<CentroMedicoBean>>() {
				}.getType();
				objResponse = gs.fromJson(strResponse, listType);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
			}
		}
		centrosMedicos = objResponse;
		
		if (objResponse != null) {
			if (objResponse.size()>0) {
				for (int i = 0; i < objResponse.size() ; i++) {
					centroMedico = objResponse.get(i);
					GeocoderResponse response = MyGeocoder.getFromLocation(centroMedico.location.coordinates.get(0), centroMedico.location.coordinates.get(1), 0);
					if (response !=null){
						if (response.status.equals("OK")){
							if (response.results.size()>0){
								centroMedico.direccion = response.results.get(0).formatted_address;
							}
						}
					}
				}
				
			} 
		} 

		return centrosMedicos;
	}

}
